package com.jee.ssm.modules.handheldMachine;

import cn.hutool.http.HttpRequest;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSON;
import com.jee.ssm.model.*;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.modules.chargeRules.services.ChargeRulesService;
import com.jee.ssm.modules.order.services.OrderService;
import com.jee.ssm.modules.posUser.services.PosUserService;
import com.jee.ssm.modules.posuserBerth.services.PosuserBerthService;
import com.jee.ssm.modules.ssm.services.AccountService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 *手持机相关的接口
 */
@RequestMapping("/handheldNachine")
@Controller
public class HandheldMachine {

    /**
     * @Description 手持机用户登录
     * @author yanzengbao
     * @date 2019/8/8 上午10:41
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Tip login(String userName,String passWord){

        Map map = new HashMap();
        map.put("userName",userName);
        map.put("passWord",passWord);
        Account account = accountService.selectByParam(map);
        if(account != null ){
            if(account.getStatus() == 0) return new Tip(2,"登录失败！此帐号已被封，请联系管理员！");

            PosUser posUser = posUserService.selectById(account.getInfoId());
            if(posUser == null) return new Tip(3,"登录失败！用户不存在！请核对登录信息！");

            List<PosuserBerth> posuserBerths = posuserBerthService.selectByUserId(posUser.getId());
            if(posuserBerths == null || posuserBerths.isEmpty()) return new Tip(4,"登录失败！请联系管理员绑定车位");

            //判断收费规则是否添加并启用
            long largeCar = chargeRulesService.countByParkAndcarType(new HashMap(){{
                put("carType",1);
                put("parkId",posUser.getParkId());
            }});
            if(largeCar <= 0) return new Tip(5,"登录失败！大车收费规则未启用！请联系管理员！");

            long smallCar = chargeRulesService.countByParkAndcarType(new HashMap(){{
                put("carType",0);
                put("parkId",posUser.getParkId());
            }});
            if(smallCar <= 0) return new Tip(5,"登录失败！小车收费规则未启用！请联系管理员！");

            return new Tip("登录成功！",posUser);
        }else{
            return new Tip(1,"登录失败！登录信息有误，请重新输入！");
        }
    }

    /**
     * @Description 获取所管辖的车位列表
     * @author yanzengbao
     * @date 2019/8/8 下午4:27
     */
    @RequestMapping(value = "/getBerthList")
    @ResponseBody
    public Tip getBerthList(String userId){
        List<Berth> berthList = new ArrayList<>();
        List<PosuserBerth> posuserBerths = posuserBerthService.selectByUserId(userId);
        if(posuserBerths != null && !posuserBerths.isEmpty()){
            for (PosuserBerth pb:posuserBerths) {
                Berth berth = getBerthInfoFromServer(pb.getBerthId());
                if(berth != null){
                    berthList.add(berth);
                }
            }
        }
        //对车位根据编号排序
        sortBerthList(berthList);
        return new Tip(berthList);
    }

    /**
     * @Description 对车位根据编号排序方法封装
     * @author yanzengbao
     * @date 2019/8/12 下午3:19
     */
    private void sortBerthList(List<Berth> berthList){
        if(berthList != null && !berthList.isEmpty()){
            Collections.sort(berthList, new Comparator<Berth>() {
                @Override
                public int compare(Berth o1, Berth o2) {
                    if(o1 == null){
                        return 1;
                    }
                    if(o2 == null || !(o2 instanceof Berth)){
                        return -1;
                    }
                    return o1.getBerthCode().compareTo(o2.getBerthCode());
                }
            });
        }
    }

    /**
     * @Description 获取平台服务器车位详情
     * @author yanzengbao
     * @date 2019/8/8 下午4:59
     */
    public Berth getBerthInfoFromServer(String berthId) {
        try {
            Props props = new Props("config/project.properties");
            String serverUrl = props.getStr("server.url");
            String method = props.getStr("getBerthInfo");
            String result = HttpRequest.get(serverUrl + method).form("berthId",berthId).execute().body();
            Berth berth = JSON.parseObject(result,Berth.class);
            if(berth != null){
                return berth;
            }else{
                return null;
            }
        }catch (Exception e){
            //e.printStackTrace();
            System.out.println("服务器断开链接！");
            return null;
        }
    }


    /**
     * @Description 获取正常可用状态的停车位列表
     * @author yanzengbao
     * @date 2019/8/12 下午3:12
     */
    @RequestMapping(value = "/getAllowBerth")
    @ResponseBody
    public Tip getallowBerth(String userId){
        List<Berth> berthList = new ArrayList<>();
        List<PosuserBerth> posuserBerths = posuserBerthService.selectByUserId(userId);
        if(posuserBerths != null && !posuserBerths.isEmpty()){
            for (PosuserBerth pb:posuserBerths) {
                Berth berth = getBerthInfoFromServer(pb.getBerthId());
                if(berth != null){
                    if(berth.getStatus() == 0){//正常
                        berthList.add(berth);
                    }
                }
            }
        }
        //排序
        sortBerthList(berthList);
        return new Tip(berthList);
    }

    /**
     * @Description 根据收费员id获取订单列表
     * @author yanzengbao
     * @date 2019/8/16 上午9:28
     */
    @RequestMapping(value = "/getOrdersByUser")
    @ResponseBody
    public Tip getOrdersByUser(String userId){
        List<Order> list = orderService.selectByPosUserId(userId);
        return new Tip(list);
    }

    /**
     * 描述： 搜索近一周没有支付状态的订单（根据停车场ID和车牌号查询）
     * 创建时间：2021/4/25  YanZengBao
     * 修改时间：2021/4/25  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/getSouSou")
    @ResponseBody
    public Tip getSouSou(String parkId,String plateNo){
        Map map = new HashMap();
        map.put("parkId",parkId);
        map.put("plateNo",plateNo);
        List<Order> orderList = orderService.selectSousou(map);
        return new Tip(orderList);
    }



    //---------------------------- property -------------------------------

    @Resource
    private PosUserService posUserService;
    @Resource
    private AccountService accountService;
    @Resource
    private PosuserBerthService posuserBerthService;
    @Resource
    private OrderService orderService;
    @Resource
    private ChargeRulesService chargeRulesService;
}
